import { pageCuesTopic, pageCuesTopicInit } from '@/services/api/api-cues-topic';
import { ReloadOutlined } from '@ant-design/icons';
import { LightFilter, ProFormSelect, ProTable } from '@ant-design/pro-components';
import { ActionType } from '@ant-design/pro-table';
import { Button, Input, Space, Tag } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import TableTopicMediaDetailsRecord from './TableTopicMediaDetailsRecord';
import TableTopicMediaDetailsSubmit from './TableTopicMediaDetailsSubmit';
import ProList from '@ant-design/pro-list';
import { parse } from '@/utils/historyUtils';

interface TableTopicMediaProps {
  mode: number;
  loading: boolean;
  industryIds: any[];
  actionRef?: ActionType;
  onRefurbish: () => void;
}

const TableTopicMedia: React.FC<TableTopicMediaProps> = (props) => {
  const userRef = useRef<ActionType>();
  const userRefList = useRef<ActionType>();
  const access = useAccess();
  const [topicId, setTopicIdState] = useState()
  useEffect(() => {
    const { topicId } = parse(location.search) as { topicId: string };
    setTopicIdState(topicId);
  }, [])
  useEffect(() => {
    if (props.loading) {
      userRef.current?.reload();
      props.onRefurbish();
    }
  }, [props.loading]);

  /**
   * 行业
   */
  const [queryParam, setQueryParamState] = useState({});
  /**
     * 行业
     */

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          key: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  const request = async (params = {}) => {
    const response = await pageCuesTopic({ mode: props.mode, ...params, ...queryParam, });
    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };


  /**
   * 加载 页面初始化信息
   * @param key
   */
  const loadPageCuesTopicInitData = async () => {
    try {
      const response = await pageCuesTopicInit({ mode: props.mode });
      if (response.code === 0) {
        setQueryOrganizationsState(readyTreeData(response.data.queryOrganizations));
      }
    } catch (error) { }
  };

  useEffect(() => {
    loadPageCuesTopicInitData();
  }, []);

  return (
    <>
      <Input.Search
        placeholder="查询标题"
        enterButton="搜索"
        allowClear
        style={{ maxWidth: 522, width: '100%', marginTop: 5 }}
        onChange={(e) => {
          setQueryParamState({ ...queryParam, name: e.target.value });
        }}
        onSearch={(value) => {
          userRefList.current?.reset();
        }}
      />
      <LightFilter
        initialValues={{}}
        onValuesChange={(value) => {
          setQueryParamState(value);
          userRefList.current?.reset();
        }}
        onFinish={async (values) => console.log(values.sex)}
      >
        <ProFormSelect
          name="recordStates"
          label="状态"
          mode="multiple"
          options={[
            {
              label: '申请',
              value: 1,
            },
            {
              label: '退回',
              value: 2,
            },

            {
              label: '废弃',
              value: 4,
            },
            {
              label: '通过',
              value: 3,
            },
          ]}
        />
        <ProFormSelect
          name="isLinkage"
          label="联动"
          options={[
            {
              label: '是',
              value: 1,
            },
            {
              label: '否',
              value: 0,
            },
          ]}
        />
      </LightFilter>
      <ProList<CuesTopicData.TopicPage>
        header={false}
        headerTitle={false}
        pagination={{
          defaultPageSize: 8,
          showSizeChanger: false,
          showTotal: false,
          style: { textAlign: 'center' },
        }}
        actionRef={userRefList}
        request={request}
        showActions="hover"
        grid={{ gutter: 18, column: 1 }}
        onItem={(record: any) => {
          return {
            onMouseEnter: () => {
            },
            onClick: () => {
            },
          };
        }}
        renderItem={(item: CuesTopicData.TopicPage, index: number) => {
          if (item.isRelease === 1) {
            return (
              <TableTopicMediaDetailsSubmit
                topicId={topicId}
                item={item}
                onRefurbish={() => {
                  userRefList.current?.reload();
                }}
                triggerMode='card'
                title=''
              />
            );
          } else {
            return (
              <TableTopicMediaDetailsRecord
                topicId={topicId}
                triggerMode={'card'}
                item={item}
                onRefurbish={() => {
                  userRefList.current?.reload();
                }}
              />
            );
          }
        }}
        rowKey={'id'}
        toolBarRender={false}
      />
    </>
  );
};

export default TableTopicMedia;
